package cn.lh.basic.controller;

import cn.lh.basic.util.FastDfsUtils;
import cn.lh.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    public JsonResult upload(@RequestPart(value = "file", required = true) MultipartFile file) {
        try {
            byte[] fileBytes = file.getBytes();
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            // 返回一个文件名
            String resultObj = FastDfsUtils.upload(fileBytes, extName);
            JsonResult.set(true, "上传成功");
            return JsonResult.setResultObject(resultObj);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.set(false, "上传失败");
        }
    }

    @DeleteMapping
    public JsonResult delete(@RequestParam(required = true, value = "path") String path) {
        try {
            String pathTem = path.substring(1);
            String groupName = pathTem.substring(0,pathTem.indexOf("/"));
            String fileName = pathTem.substring(path.indexOf("/")+1);
            FastDfsUtils.delete(groupName, fileName);
            return JsonResult.set(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "删除失败");
        }

    }
}
